package org.jeecg.modules.alarm.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhouwr.common.enums.NoticeType;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.modules.alarm.entity.ActuatorNotification;
import org.jeecg.modules.alarm.entity.AlarmConfigActuator;
import org.jeecg.modules.alarm.mapper.ActuatorNotificationMapper;
import org.jeecg.modules.alarm.service.IActuatorNotificationService;
import org.jeecg.modules.alarm.service.IAlarmActuatorService;
import org.jeecg.modules.alarm.service.IAlarmConfigService;
import org.jeecg.modules.alarm.vo.AlarmConfigVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: forallcn-iotps
 * @description: IActuatorNotificationService
 * @author: zhouwr
 * @create: 2021-03-15 21:37
 * @version：1.0
 **/
@Service
@Slf4j
public class ActuatorNotificationServiceImpl extends ServiceImpl<ActuatorNotificationMapper, ActuatorNotification> implements IActuatorNotificationService {

    @Autowired
    private IActuatorNotificationService notificationService;
    @Autowired
    private IAlarmActuatorService actuatorService;
    @Autowired
    private IAlarmConfigService alarmConfigService;

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Override
    public void sendNotification(String actuatorId) {
        /* 1、根据执行器id，获取系统消息配置信息，执行器的id和消息通知id一值 */
        ActuatorNotification notification = notificationService.getById(actuatorId);
        log.info("notification >>> {}", notification);
        /* 2、判断消息类型，网络服务消息在iot模块中，其它为系统消息 */
        if (notification.getNoticeType().equals(NoticeType.INTERNET_SERVICE)) {
            // TODO 获取网络服务模板
        } else {
            /* 3、其它为系统消息：根据消息模板code，获取去系统消息模板 */
            Map<String, String> msgMap = this.alarmConfigIntoMap(actuatorId);
            sysBaseAPI.sendMessage(notification.getNoticeTemplateCode(), msgMap);
        }

    }

    @Cacheable(cacheNames = "alarm:config:info", key = "#actuatorId")
    public Map<String, String> alarmConfigIntoMap(String actuatorId) {
        Map<String, String> map = new HashMap<String, String>();
        AlarmConfigActuator actuator = actuatorService.getById(actuatorId);
        if (actuator != null) {
            AlarmConfigVo alarmConfigVo = alarmConfigService.buildAlarmConfigVoById(actuator.getAlarmConfigId());
            map = alarmConfigVo.toMap();
        }
        return map;
    }
}
